<template>
    <!-- PV 折线图容器 -->
    <div id="lineBarChat" class="overflow-hidden w-full h-80"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, watch } from 'vue'

// 暴露value变量 接受数据
const props = defineProps({
    value: {
        type: Object,
        default: null
    }
})

// 初始化折线和直方图
const initLineBarChat = () => {
    // 转移数据
    let data = props.value
    let pvDates = data.pvDates
    let pvCounts = data.pvCounts
    // 获取最大点击次数与最小点击次数
    
    let maxCount = 0
    let minCount = (1 << 30)
    if (pvCounts) {
        for (const item of pvCounts) {
            if (item > maxCount) maxCount = item
            if (item < minCount) minCount = item
        }
    } else {
        minCount = 10
    }

    if (minCount == maxCount && maxCount > 10) minCount = maxCount - 10
    else if (minCount == maxCount && maxCount == 0) maxCount = 10
    
    // 初始化
    let chartDom = document.getElementById('lineBarChat');
    let myChart = echarts.init(chartDom);
    let option;
    option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        legend: {
            data: ['日点击量(折线图)', '日点击量(直方图)']
        },
        xAxis: [
            {
                type: 'category',
                data: pvDates,
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '日点击量(折线图)',
                min: minCount,
                max: maxCount,
                interval: Math.round((maxCount - minCount) / 5),
                axisLabel: {
                    formatter: '{value} 次'
                }
            },
            {
                type: 'value',
                name: '日点击量(直方图)',
                min: minCount,
                max: maxCount,
                interval: Math.round((maxCount - minCount) / 5),
                axisLabel: {
                    formatter: '{value} 次'
                }
            }
        ],
        series: [
            {
                name: '日点击量(直方图)',
                type: 'bar',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + ' 次';
                    }
                },
                data: pvCounts
            },
            {
                name: '日点击量(折线图)',
                type: 'line',
                yAxisIndex: 1,
                tooltip: {
                    valueFormatter: function (value) {
                        return value + ' 次';
                    }
                },
                data: pvCounts
            }
        ]
    };

    option && myChart.setOption(option);
}

// 监听value 变化时初始化
watch(() => props.value, () => initLineBarChat())
</script>